//
//  STRenewViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/12/19.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "STRenewViewController.h"

#import "CityChooserViewController.h"
#import "RenewDateChooserViewController.h"
#import "PayViewController.h"

#import "RenewChooseCityCell.h"

@interface STRenewViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) STRenewViewModel* viewModel;

// UI

//IBOutlet
@property (nonatomic, weak) IBOutlet UILabel* dateLabel;
@property (nonatomic, weak) IBOutlet UILabel* chooseCityNumLabel;
@property (nonatomic, weak) IBOutlet UILabel* chargeLabel; 
@property (nonatomic, weak) IBOutlet UILabel* chosedNumLabel;
@property (nonatomic, weak) IBOutlet UILabel* priceLabel;
@property (nonatomic, weak) IBOutlet UILabel* originPriceLabel;
@property (nonatomic, weak) IBOutlet UIButton* cityChooseBtn;
@property (nonatomic, weak) IBOutlet UIButton* dateChooseBtn;
@property (nonatomic, weak) IBOutlet UIButton* payButton;
@property (nonatomic, weak) IBOutlet UIButton* allChooseButton;
@property (nonatomic, weak) IBOutlet UISwitch* chargeSwitchBtn;
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;

@end

@implementation STRenewViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[RenewChooseCityCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
}

- (void)initUI
{
    @weakify(self);
    
}

#pragma mark - Override
- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         [self.viewModel checkInit];
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    RAC(self.dateLabel, text) = [RACObserve(self.viewModel, chooseDateIndex) map:^id(id value)
    {
        NSArray* dates = @[@"三个月", @"六个月", @"一年", @"两年"];
        
        NSInteger chooseDateIndex = [value integerValue];
        
        if (chooseDateIndex == -1)
        {
            return @"请选择 >";
        }
        else
        {
            return dates[chooseDateIndex];
        }
    }];
    RAC(self.chooseCityNumLabel, text) = RACObserve(self.viewModel, strChooseCityNum);
    RAC(self.chosedNumLabel, text) = RACObserve(self.viewModel, strSelectChooseNum);
    RAC(self.chargeLabel, text) = RACObserve(self.viewModel, charge);
    RAC(self.priceLabel, text) = RACObserve(self.viewModel, price);
    RAC(self.originPriceLabel, text) = RACObserve(self.viewModel, originPrice);
    
    self.viewModel.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath) {
        @strongify(self);
        
        [self.viewModel.selectCityChooseCmd execute:indexPath];
        
        return [RACSignal empty];
    }];
    
    RAC(self.payButton, backgroundColor) = [RACObserve(self.viewModel, isCanPay) map:^id(id value) {
        BOOL isCanPay = [value boolValue];
        
        return isCanPay ? UIColorHex(#008f58) : UIColorHex(#f0f0f0);
    }];
    self.payButton.rac_command = self.viewModel.payCmd;
    [[self.viewModel.payCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self _push2PayVC:x];
     }];
    
    self.cityChooseBtn.rac_command = self.viewModel.cityChooseCmd;
    [[self.viewModel.cityChooseCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2CityChooseVC];
    }];
    
    self.dateChooseBtn.rac_command = self.viewModel.dateChooseCmd;
    [[self.viewModel.dateChooseCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self _push2DateChooseVC];
     }];
    
    RAC(self.allChooseButton, selected) = RACObserve(self.viewModel, isAllChoose);
    self.allChooseButton.rac_command = self.viewModel.allChooseCmd;
    
    [[self.chargeSwitchBtn rac_newOnChannel] subscribeNext:^(id value)
    {
        @strongify(self);
        BOOL flag = [value boolValue];
        
        self.viewModel.isChargeSwitch = flag;
    }];
}

- (UITableView*)customTableView
{
    return self.currentTableView;
}

#pragma mark - 更新初始化 操作
- (void)_setupSubViews
{
    
}

- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    @weakify(self);
    
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

//// 下拉刷新
- (void)tableViewDidTriggerHeaderRefresh{
    /// 先调用父类的加载数据
    [super tableViewDidTriggerHeaderRefresh];
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([RenewChooseCityCell class])];
}

/// config  data
- (void)configureCell:(RenewChooseCityCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(RenewChooseCityCellModel *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell bindViewModel:object];
}

/// 文本内容区域
//- (UIEdgeInsets)contentInset
//{
//    return UIEdgeInsetsZero;
//}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    return [self.viewModel.dataSource[indexPath.row] cellHeight];
}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}


#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_push2PayVC:(NSDictionary*)orderInfo
{
    NSString* money = [NSString decimalwithFormat:@"0.00" floatV:[orderInfo[@"pay_price"] floatValue]];
    
    PayViewModel* vm = [[PayViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"支付"}];
    vm.pay4Type = 1;
    vm.orderID = orderInfo[@"spread_id"];
    vm.orderSN = orderInfo[@"spread_sn"];
    vm.money = money;
    PayViewController* vc = [[PayViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2CityChooseVC
{
    @weakify(self);
    
    CityChooserViewModel* vm = [[CityChooserViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"选择城市"}];
    vm.cityAreaIDs = self.viewModel.cityAreaIDs;
    [[vm.finishCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self.viewModel.refreshCityCmd execute:x];
    }];
    CityChooserViewController* vc = [[CityChooserViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2DateChooseVC
{
    @weakify(self);
    
    RenewDateChooserViewModel* vm = [[RenewDateChooserViewModel alloc] initWithParams:@{}];
    [vm.finishCmd.executionSignals.switchToLatest subscribeNext:^(id x)
    {
        @strongify(self);
        
        self.viewModel.chooseDateIndex = [x integerValue];
    }];
    RenewDateChooserViewController* vc = [[RenewDateChooserViewController alloc] initWithViewModel:vm];
    vc.view.backgroundColor = [UIColor clearColor];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
    else
    {
        vc.modalPresentationStyle = UIModalPresentationCurrentContext;
    }
    [self presentViewController:vc animated:YES completion:^
     {
         vc.view.backgroundColor = UIColorHex(#0000000f);
     }];
}

@end
